<template>
  <div>
    <vxe-toolbar>
      <template #buttons>
        <el-button type="success" icon="el-icon-plus" size="medium" @click="insertEvent">新增记录</el-button>
        <!-- <el-button type="success" icon="el-icon-printer" size="medium" @click="printEvent">打印</el-button> -->
        <vxe-input style="float: right;" v-model.trim.lazy="filterName" type="search" placeholder="快捷检索"
          @input="searchEvent"></vxe-input>
      </template>
    </vxe-toolbar>
    <vxe-table resizable ref="XTable" show-overflow border max-height="800" stripe highlight-hover-row
      highlight-current-row :loading="loading" :data="dataList" @sort-change="sortChange">
      <vxe-table-column field="coach" title="在训教练" sortable></vxe-table-column>
      <vxe-table-column field="inOrg" title="接收单位" sortable></vxe-table-column>
      <vxe-table-column field="towar" title="走向" sortable></vxe-table-column>
      <vxe-table-column field="sportDate" title="训练开始时间" sortable></vxe-table-column>
      <vxe-table-column field="transportDate" title="输送时间" sortable></vxe-table-column>
      <vxe-table-column field="outOrg" title="输出单位名称" sortable></vxe-table-column>
      <vxe-table-column field="trSport" title="输送前运动项目" sortable></vxe-table-column>
      <vxe-table-column field="trSportItem" title="输送前运动小项" sortable></vxe-table-column>
      <vxe-table-column field="allSport" title="吸收项目" sortable></vxe-table-column>
      <vxe-table-column field="allSportItem" title="吸收小项" sortable></vxe-table-column>
      <vxe-table-column field="coachName" title="教练员" sortable></vxe-table-column>
      <vxe-table-column field="memo" title="备注" sortable></vxe-table-column>
      <vxe-table-column field="" title="操作" width="110">
        <template #default="{ row,rowIndex }">
          <el-button @click="editEvent(row,rowIndex)" type="success" size="medium" icon="el-icon-edit" circle></el-button>
          <el-button @click="deleteEvent(row)" type="danger" size="medium" icon="el-icon-delete" circle></el-button>
        </template>
      </vxe-table-column>
    </vxe-table>
    <vxe-pager :loading="loading" :current-page="page.currentPage" :page-size="page.pageSize" :total="page.totalResult"
      :layouts="['PrevPage', 'JumpNumber', 'NextPage', 'FullJump', 'Sizes', 'Total']" @page-change="handlePageChange">
    </vxe-pager>
    <vxe-modal v-model="insertModal" title="走向输送">
      <template #default>
        <el-form inline-message ref="insertForm" :rules="rules" :model="insertForm" label-width="110px">
          <el-form-item label="在训教练" prop="coachId">
            <el-select v-model="insertForm.coachId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_coach" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="接收单位" prop="inOrgId">
            <el-select v-model="insertForm.inOrgId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allOrg" :key="index"></el-option>
            </el-select>
            <el-link v-if="!inOrgInsertShow" @click="inOrgInsertShow=true" style="font-size: 80%;" icon="el-icon-plus"
              type="success">未找到需要的机构？点击该行新增 <i class="el-icon-plus el-icon--right"></i> </el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入接收单位" v-model="allOrg" class="input-with-select">
              <el-button @click="allOrgInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="走向" prop="towardId">
            <el-select v-model="insertForm.towardId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_towar" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="训练开始时间" prop="sportDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.sportDate" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="输送时间" prop="transportDate">
            <el-date-picker type="date" placeholder="选择日期" v-model="insertForm.transportDate" style="width: 100%;">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="输出单位名称" prop="outOrgId">
            <el-select v-model="insertForm.outOrgId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allOrg" :key="index"></el-option>
            </el-select>
            <el-link v-if="!outOrgInsertShow" @click="outOrgInsertShow=true" style="font-size: 80%;" icon="el-icon-plus"
              type="success">未找到需要的机构？点击该行新增 <i class="el-icon-plus el-icon--right"></i> </el-link>
            <el-input v-else style="margin-top: 10px;" placeholder="请输入输出单位" v-model="allOrg" class="input-with-select">
              <el-button @click="allOrgInsert" slot="append" icon="iconfont icon-save"></el-button>
            </el-input>
          </el-form-item>
          <el-form-item label="输送前运动项目" prop="trSportId">
            <el-select v-model="insertForm.trSportId" @change="sportChange" filterable clearable style="width: 100%;"
              placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_sport" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="输送前运动小项" prop="trSportItemId">
            <el-select v-model="insertForm.trSportItemId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in sportItemData"
                :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="吸收项目" prop="allSportId">
            <el-select v-model="insertForm.allSportId" @change="allSportChange" filterable clearable
              style="width: 100%;" placeholder="请选择">
              <el-option :label="item" :value="key" v-for="(item,key,index) in dict_allSport" :key="index"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="吸收小项" prop="allSportItemId">
            <el-select v-model="insertForm.allSportItemId" filterable clearable style="width: 100%;" placeholder="请选择">
              <el-option :label="item.name" :value="item.sportItemId" v-for="(item,index) in allSportItemData"
                :key="index">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教练员" prop="coachName">
            <el-input v-model="insertForm.coachName"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="memo">
            <el-input v-model="insertForm.memo"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="warning" size="small" @click="insertModal = false">取消</el-button>
            <el-button type="success" size="small" icon="el-icon-s-promotion" @click="insertSave">保存</el-button>
          </el-form-item>
        </el-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
  import {
    transport_select,
    sport_item_by_sportId,
    transport_insert,
    transport_update,
    transport_delete,
    all_org_insert
  } from '@/api/person.js'
  import {
    coachByOrgIgnoreRole,
    sport_by_org,
    sport_item,
    all_org,
    toward,
    get_sport
  } from '@/api/dict.js'
  export default {
    props: ['pId'],
    data() {
      return {
        defaultDataList: [],
        dataList: [],
        page: {
          currentPage: 1,
          pageSize: 10,
          totalResult: 0
        },
        loading: false,
        filterName: '',
        insertModal: false,
        dict_sport: {},
        dict_sportItem: {},
        dict_coach: {},
        dict_allOrg: {},
        dict_towar: {},
        dict_allSport: {},
        dict_allSportItem: {},
        insertForm: {
          coachId: '',
          inOrgId: '',
          towardId: '',
          sportDate: '',
          transportDate: '',
          outOrgId: '',
          trSportId: '',
          trSportItemId: '',
          allSportId: '',
          allSportItemId: '',
          coachName: '',
          memo: '',

        },
        sportItemData: [],
        allSportItemData: [],
        rules: {
          openDate: [{
            required: true,
            message: '这是必填项',
            trigger: 'blur'
          }, ],
        },
        isInsert: true,
        transportId: '',
        allOrg: '',
        inOrgInsertShow: false,
        outOrgInsertShow: false,
        search: false,
        currentIndex: null,
      }
    },
    created() {
      this.init_dict().then(() => {
        this.transport_select()
      })
    },
    watch: {
      filterName(val) {
    	if(!val){
    	  this.page = {
    	  currentPage: 1,
    	  pageSize: 10,
    	  totalResult: 0,
    	  }
    	  this.search = false
    	  this.findList()
    	}
      }
    },
    computed: {
      openDateValid() {
        if (this.insertForm.openDate && this.insertForm.closeDate) {
          if (this.insertForm.openDate > this.insertForm.closeDate) {
            this.$message.error('开始时间必须小于结束时间！')
            return false
          } else {
            return true
          }
        } else {
          return true
        }
      }
    },
    watch: {
      inOrgInsertShow(val) {
        if (val) {
          this.outOrgInsertShow = false
          this.allOrg = ''
        }
      },
      outOrgInsertShow(val) {
        if (val) {
          this.inOrgInsertShow = false
          this.allOrg = ''
        }
      }
    },
    methods: {
      allOrgInsert() {
        all_org_insert({
          name: this.allOrg
        }).then(res => {
          if (res.code === 200) {
            this.$message.success('添加成功')
            all_org().then(res => {
              this.dict_allOrg = res
            })
          } else {
            this.$message.error(res.message)
          }
          if (this.inOrgInsertShow) {
            this.inOrgInsertShow = false
          } else if (this.outOrgInsertShow) {
            this.outOrgInsertShow = false
          } else {
            this.inOrgInsertShow = false
            this.outOrgInsertShow = false
          }
          this.allOrg = ''
        })
      },
      deleteEvent(row) {
        this.$confirm('此操作将永久删除该条记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          transport_delete({
            pId: this.pId,
            data: {
              transportId: row.transportId
            }
          }).then(res => {
            if (res.code === 200) {
              this.defaultDataList.forEach((item,index)=>{
              	if(item.transportId == row.transportId){
              	  this.defaultDataList.splice(index,1)
              	}
              })
              this.init_data(this.defaultDataList)
              this.findList()
              this.$message.success('删除成功！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      editEvent(row,rowIndex) {
        this.currentIndex = rowIndex
        this.transportId = row.transportId
        this.insertForm.coachId = row.coachId == 0 ? '' : row.coachId + ''
        this.insertForm.inOrgId = row.inOrgId == 0 ? '' : row.inOrgId + ''
        this.insertForm.towardId = row.towardId == 0 ? '' : row.towardId + ''
        this.insertForm.sportDate = row.sportDate
        this.insertForm.transportDate = row.transportDate
        this.insertForm.outOrgId = row.outOrgId == 0 ? '' : row.outOrgId + ''
        this.insertForm.trSportId = row.trSportId == 0 ? '' : row.trSportId + ''
        this.sportChange()
        this.insertForm.trSportItemId = row.trSportItemId == 0 ? '' : row.trSportItemId
        this.insertForm.allSportId = row.allSportId == 0 ? '' : row.allSportId + ''
        this.allSportChange()
        this.insertForm.allSportItemId = row.allSportItemId == 0 ? '' : row.allSportItemId
        this.insertForm.coachName = row.coachName
        this.insertForm.memo = row.memo
        this.isInsert = false
        this.insertModal = true
      },
      insertSave() {
        this.$refs.insertForm.validate((valid) => {
          if (valid && this.openDateValid) {
            let data = {}
            if (this.insertForm.coachId) data.coachId = this.insertForm.coachId
            if (this.insertForm.inOrgId) data.inOrgId = this.insertForm.inOrgId
            if (this.insertForm.towardId) data.towardId = this.insertForm.towardId
            if (this.insertForm.sportDate) data.sportDate = this.$moment(this.insertForm.sportDate).format(
              'YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.transportDate) data.transportDate = this.$moment(this.insertForm.transportDate)
              .format('YYYY-MM-DD') + ' 00:00:00'
            if (this.insertForm.outOrgId) data.outOrgId = this.insertForm.outOrgId
            if (this.insertForm.trSportId) data.trSportId = this.insertForm.trSportId
            if (this.insertForm.trSportItemId) {
              data.trSportItemId = this.insertForm.trSportItemId
            } else {
              data.trSportItemId = 0
            }
            if (this.insertForm.allSportId) data.allSportId = this.insertForm.allSportId
            if (this.insertForm.allSportItemId) {
              data.allsportItemId = this.insertForm.allSportItemId
            } else {
              data.allsportItemId = 0
            }
            if (this.insertForm.coachName) data.coachName = this.insertForm.coachName
            if (this.insertForm.memo) data.memo = this.insertForm.memo
            data.pId = this.pId
            if (this.isInsert) {
              transport_insert(data).then(res => {
                if (res.code === 200) {
                  this.dataList.unshift(res.data)
                  this.defaultDataList.push(res.data)
                  this.init_data(this.defaultDataList)
                  this.page.totalResult+=1
                  this.$refs.XTable.setCurrentRow(this.dataList[0])
                  this.$message.success('保存成功')
                  this.insertSuccess = true
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            } else {
              data.transportId = this.transportId
              transport_update(data).then(res => {
                if (res.code === 200) {
                  Object.assign(this.dataList[this.currentIndex],res.data)
                  this.defaultDataList.forEach(item=>{
                  	if(res.data.transportId == item.transportId){
                  	  Object.assign(item,res.data)
                  	}
                  })
                  this.init_data(this.defaultDataList)
                  this.$message.success('修改成功')
                  this.insertModal = false
                } else {
                  this.$message.error(res.message)
                }
              })
            }
          } else {
            return false;
          }
        })
      },
      insertEvent() {
        this.insertForm = {
          coachId: '',
          inOrgId: '',
          towardId: '',
          sportDate: '',
          transportDate: '',
          outOrgId: '',
          trSportId: '',
          trSportItemId: '',
          allSportId: '',
          allSportItemId: '',
          coachName: '',
          memo: '',

        }
        this.isInsert = true
        this.insertModal = true
      },
      sportChange() {
        this.insertForm.trSportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.trSportId
        }).then(res => {
          if (res.code === 200) {
            this.sportItemData = res.data
          }
        })
      },
      allSportChange() {
        this.insertForm.allSportItemId = ''
        sport_item_by_sportId({
          sportId: this.insertForm.allSportId
        }).then(res => {
          if (res.code === 200) {
            this.allSportItemData = res.data
          }
        })
      },
      printEvent() {
        let topHtml = '<h2>走向输送</h2>'
        this.searchEvent()
        setTimeout(() => {
          this.$refs.XTable.print({
            sheetName: '走向输送',
            beforePrintMethod: ({
              content
            }) => {
              return topHtml + content
            }
          })
        }, 1000)
      },
      searchEvent() {
        const filterName = this.$XEUtils.toValueString(this.filterName).trim().toLowerCase()
        if (filterName) {
          const filterRE = filterName
          const searchProps = this.searchProps
          const rest = this.defaultDataList.filter(item => searchProps.some(key => this.$XEUtils.toValueString(item[
            key]).toLowerCase().indexOf(filterName) > -1))
          this.dataList = rest.map(row => {
            const item = Object.assign({}, row)
            searchProps.forEach(key => {
              item[key] = this.$XEUtils.toValueString(item[key]).replace(filterRE, match => match)
            })
            return item
          })
          this.page = {
          	currentPage: 1,
          	pageSize: this.dataList.length,
          	totalResult: this.dataList.length
            }
            this.search = true
        } else {
          this.dataList = this.defaultDataList
        }
      },
      transport_select() {
        transport_select(this.pId).then(res => {
          if (res.code === 200 && res.data.length != 0) {
            let data = res.data
            this.init_data(data)
            this.$emit('playerTransportDataPrint', this.defaultDataList)
          } else {
            this.defaultDataList = []
          }
        }).then(() => {
          this.findList()
        })
      },
      init_data(data) {
        if(data.length==0) return
        data.forEach(item => {
          item.coach = this.dict_coach[item.coachId]
          item.inOrg = this.dict_allOrg[item.inOrgId]
          item.towar = this.dict_towar[item.towardId]
          item.sportDate = this.$moment(item.sportDate).format('YYYY-MM-DD') == 'Invalid date' ? '' :
            this.$moment(item.sportDate).format('YYYY-MM-DD')
          item.transportDate = this.$moment(item.transportDate).format('YYYY-MM-DD') ==
            'Invalid date' ? '' : this.$moment(item.transportDate).format('YYYY-MM-DD')
          item.outOrg = this.dict_allOrg[item.outOrgId]
          item.trSport = this.dict_sport[item.trSportId]
          item.trSportItem = this.dict_sportItem[item.trSportItemId]
          item.allSport = this.dict_allSport[item.allSportId]
          item.allSportItem = this.dict_sportItem[item.allSportItemId]

        })
        this.searchProps = Object.keys(data[0])
        this.defaultDataList = data
      },
      init_dict() {
        return new Promise((resolve, reject) => {
          coachByOrgIgnoreRole().then(res => {
            this.dict_coach = res
            resolve()
          }).then(() => {
            sport_by_org().then(res => {
              this.dict_sport = res
              resolve()
            })
          }).then(() => {
            sport_item().then(res => {
              this.dict_sportItem = res
              resolve()
            })
          }).then(() => {
            all_org().then(res => {
              this.dict_allOrg = res
              resolve()
            })
          }).then(() => {
            toward().then(res => {
              this.dict_towar = res
              resolve()
            })
          }).then(() => {
            get_sport().then(res => {
              this.dict_allSport = res
              resolve()
            })
          })
        })
      },
      handlePageChange({
        currentPage,
        pageSize
      }) {
        this.page.currentPage = currentPage
        this.page.pageSize = pageSize
        this.findList()
      },
      sortChange() {
      	if(!this.search){
          this.page.currentPage = 1
      	  this.page.pageSize = this.defaultDataList.length
      	  this.findList()
      	}else{
      	  this.page.pageSize = this.dataList.length
      	}
      },
      findList() {
        this.loading = true
        setTimeout(() => {
          if (this.insertSuccess) {
            this.page.totalResult = this.defaultDataList.length
            this.page.currentPage = Math.ceil(this.page.totalResult / this.page.pageSize)
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
            this.$refs.XTable.setCurrentRow(this.dataList[this.dataList.length - 1])
            this.insertSuccess = false
          } else {
            this.page.totalResult = this.defaultDataList.length
            this.dataList = this.defaultDataList.slice((this.page.currentPage - 1) * this.page
              .pageSize, this.page.currentPage * this.page.pageSize)
          }
          this.loading = false
        }, 300)
      },
    }
  }
</script>

<style lang="scss" scoped>

</style>
